package com.myapp.handler;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

import org.apache.log4j.Logger;

import com.myapp.Logical.interfaces.ILogical;
import com.myapp.msg.base.BaseMsg;
import com.myapp.msg.define.MsgConfigBean;

/**
 * Servlet Filter implementation class MsgFilter
 */
@WebFilter(filterName = "msg filter", description = "消息过滤器", urlPatterns = {
		"/hr", "/hr1" }, asyncSupported = true)
public class MsgFilter implements Filter {
	// 日志
	private Logger logger = Logger.getLogger(MsgFilter.class);

	/**
	 * Default constructor.
	 */
	public MsgFilter() {
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		try {
			// 启动异步线程，不阻塞主线程
//			AsyncContext ctx = request.startAsync(request, response);
			if (this.initMsg(request)) {// 合法
				// 向下传递
				chain.doFilter(request,response);
//				chain.doFilter(ctx.getRequest(), ctx.getResponse());
//				ctx.complete();
			}
		} catch (InstantiationException e) {
			logger.error("Message instance error!", e);
		} catch (IllegalAccessException e) {
			logger.error("Message instance error!", e);
		} catch (IOException e) {
			logger.error("Read data error!", e);
		}
	}

	/**
	 * 初始化消息
	 * 
	 * @param is
	 *            消息流
	 * @return 消息bean
	 * 
	 * @throws IOException
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 */
	private boolean initMsg(ServletRequest request) throws IOException,
			InstantiationException, IllegalAccessException {
		// ServletRequest request = ctx.getRequest();
		InputStream is = request.getInputStream();
		DataInputStream dis = new DataInputStream(is);
		// 消息解码
		BaseMsg msg = Decoder.decode(dis);
		dis.close();
		is.close();

		// 如果消息不为空
		if (msg != null) {
			MsgConfigBean msgConfigBean = msg.getMsgConfigBean();
			// 初始化业务类
			ILogical logical = null;
			if (msgConfigBean != null
					&& msgConfigBean.getLogicalClass() != null && msg != null) {
				logical = msgConfigBean.getLogicalClass().newInstance();
			}

			if (msg != null && logical != null && msgConfigBean != null) {
				msg.setMsgConfigBean(msgConfigBean);
				request.setAttribute("msg", msg);
				request.setAttribute("logical", logical);
				return true;
			}
		}

		return false;
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
	}

}
